﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace CrmClient.QueryConvert
{
    internal class PropertiesMap : IEnumerable<PropertyMap>
    {
        private List<PropertyMap> _items = new List<PropertyMap>();

        public void Add(PropertyMap item)
        {
            if (_items.Contains(item))
                throw new InvalidOperationException("Такая запись уже добавлена");
            _items.Add(item);
        }

        public int Count
        {
            get { return _items.Count; }
        }

        public PropertyMap this[int i]
        {
            get { return _items[i]; }
        }

        public PropertyMap this[string classPropName]
        {
            get { return _items.Single(i => i.ClassPropName == classPropName); }
        }

        public bool Contains(CrmAttrName crmAttrName)
        {
            return _items.Any(i => i.CrmAttr.Equals(crmAttrName));
        }

        public PropertiesMap CreateUnion(PropertiesMap second)
        {
            var res = new PropertiesMap();
            foreach (var item in this)
                res.Add(item);
            foreach (var item in second)
                if (!res.Contains(item))
                    res.Add(item);
            return res;
        }

        public IEnumerator<PropertyMap> GetEnumerator()
        {
            return _items.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public PropertiesMap Clone()
        {
            var res = new PropertiesMap();
            foreach (var item in this)
                res.Add(item.Clone());
            return res;
        }
    }
}
